package org.scboy.dbms.service.imp;

import java.util.List;

import org.scboy.coobi.sql.factory.EntityFactory;
import org.scboy.dbms.dao.BaseDictionaryInfoDao;
import org.scboy.dbms.dao.InterLangDao;
import org.scboy.dbms.service.InterLangService;
import org.scboy.utils.entitys.coobi.Model;
import org.scboy.utils.entitys.coobi.Page;
import org.scboy.utils.enums.coobi.OrderType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class InterLangServiceImp implements InterLangService {

	@Autowired
	EntityFactory factory;
	
	@Override
	public Page page(Model model) {
		InterLangDao dao=factory.getDao(InterLangDao.class);
		model.orderBy("sortIndex");
		return dao.page(model);
	}

	@Override
	public Model get(String lang) {
		InterLangDao dao=factory.getDao(InterLangDao.class);
		return dao.get(Model.create().add("lang", lang));
	}

	@Override
	public boolean add(Model model) {
		InterLangDao dao=factory.getDao(InterLangDao.class);
		if(dao.count(Model.create().add("lang", model.getString("lang")))>0) {
			return false;
		}
		
		Integer sortIndex=dao.max(new String[] {"sortIndex"},Model.create()).getInt("sortIndex");
		if(sortIndex==null) {
			sortIndex=0;
		}else {
			sortIndex+=1;
		}
		model.add("sortIndex", sortIndex);
		int count=dao.insert(model);
		if(count>0) {
			return true;
		}else {
			return false;
		}
	}

	@Override
	public boolean update(Model model) {
		InterLangDao dao=factory.getDao(InterLangDao.class);
		int count=dao.update(model);
		if(count>0) {
			return true;
		}else {
			return false;
		}
	}

	@Override
	public boolean delete(String lang) {
		InterLangDao dao=factory.getDao(InterLangDao.class);
		int count=dao.delete(Model.create().add("lang", lang));
		if(count>0) {
			return true;
		}else {
			return false;
		}
	}

	@Override
	public List<Model> list() {
		InterLangDao dao=factory.getDao(InterLangDao.class);
		return dao.select(Model.create().orderBy("sortIndex"));
	}

	@Override
	public boolean sort(String lang, int type) {
		BaseDictionaryInfoDao dao=factory.getDao(BaseDictionaryInfoDao.class);
		Model model=dao.get(Model.create().add("lang", lang));
		Model lastModel=null;
		String sortKey="sortIndex";
		String idKey="lang";
		//降序
		if(type==0) {
			//查询下面一个系统
			lastModel=dao.get(Model.create().GT(sortKey, model.getInt(sortKey)).orderBy(sortKey));
			
		}else {
			//升序
			lastModel=dao.get(Model.create().LT(sortKey, model.getInt(sortKey)).orderBy(sortKey,OrderType.DESC));
			
		}
		if(lastModel!=null) {
			dao.update(Model.create().add(sortKey, lastModel.getInt(sortKey)),Model.create().add(idKey, lang));
			dao.update(Model.create().add(sortKey, model.getInt(sortKey)),Model.create().add(idKey, lastModel.getString(idKey)));
		}
		return true;
	}

}
